<template>
	<view class="container">
		<uni-forms ref="form" :value="formData" err-show-type="toast">
			<uni-forms-item name="mobile" :label="('新手机号码')" required="">

				<view class="phone-input">
					<view class="country-code" @click="toggleDropdown">
						+{{ selectedCode }} <text>▼</text>
					</view>
					<uni-easyinput :placeholder="('请输入新手机号码')" focus v-model="formData.mobile" @input="inputMobile"
						trim />
				</view>
				<view v-if="dropdownVisible" class="dropdown">
					<view v-for="(code, index) in codes" :key="index" @click="selectCode(code)" class="dropdown-item">
						+{{ code }}
					</view>
				</view>
			</uni-forms-item>
			<uni-forms-item name="code">
				<uni-id-pages-sms-form v-if="is86" focusCaptchaInput v-model="formData.code" type="login-by-sms"
					ref="smsCode" :phone="formData.mobile"></uni-id-pages-sms-form>
				<view class="not-86-box" v-else>
					<text>请确保手机通讯正常。</text>
				</view>

			</uni-forms-item>

			<view class="note-box" style="padding-top: 100rpx;">
				<text v-if="is86">{{$w('设置后，将用于登录、接收信息等，具有唯一性。')}}</text>
				<text v-else>设置后，将用于通话、接收信息等，具有唯一性。</text>
			</view>
			<!-- <view class="">
				<button type="default" @click="test">test </button>
			</view> -->
			<view class="uni-button-group">
				<button type="primary" class="uni-button" @click="preSubmit">{{$w('提交')}}</button>
			</view>
		</uni-forms>
		<uv-toast-wjf ref="uvToastWjf"></uv-toast-wjf>
		<uv-modal ref="uvModal" :title="uvModelParam.title" :content='uvModelParam.content' :align="uvModelParam.align"
			:confirmText="uvModelParam.confirmText" :cancelText="uvModelParam.cancelText"
			:showCancelButton="uvModelParam.showCancelButton"></uv-modal>
	</view>
</template>

<script>
	import {
		mapActions,
	} from 'vuex';
	import commMixinWjf from '@/common/mixin/common-mixin-wjf.js'
	// import rules from './validator.js';
	import mixinRules from './mixin-rules-mobile';
	import {
		mutations as uniIdMutations
	} from '@/uni_modules/uni-id-pages/common/store.js';
	const db = uniCloud.database();
	const uniIdCo = uniCloud.importObject("uni-id-co", {
		errorOptions: {
			type: 'toast'
		}
	})
	const wjfCo = uniCloud.importObject('wjf-co', {
		customUI: false,
		loadingOptions: {
			title: '', // 只保留转圈状态
		},
		errorOptions: {
			type: 'toast'
		}
	})
	const ap126Co = uniCloud.importObject('ap126-co', {
		customUI: false,
		loadingOptions: {
			title: '', // 只保留转圈状态
		},
		errorOptions: {
			type: 'toast'
		}
	})
	import i18nMixin from '../i18n/i18n-mixin.js'
	export default {
		mixins: [commMixinWjf, i18nMixin, mixinRules],
		data() {
			return {
				formData: {
					mobile: "",
					code: '',
					type: 'login',
					"captcha": ""
				},
				countries: ['中国', '哈萨克斯坦', '吉尔吉斯斯坦'],
				codes: ['86', '7', '996'],
				selectedCode: '86', // 默认选择中国区号
				phoneNumber: '',
				isSame: false, //输入的手机号是否与原手机号相同,如果相同则提示且不做变更操作
				is86: true, //是否中国号码 国内国外号码处理方式不同
				dropdownVisible: false, // 控制下拉框的显示
				focus: true,
				key: 0,
				isSubmit: false,
				sendedCode: '', //发送的验证码
				accountInfo: null,
			}
		},
		async onLoad() {
			// await uniIdCo.getAccountInfo().then(res => {
			// 	this.accountInfo = res
			// 	console.log('onLoad', this.accountInfo);
			// })

		},
		computed: {
			userInfo() {
				return this.$store.state.user.userInfo
			}
		},
		onShow() {
			// console.log('onShow');
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
			this.selectedCode = this.userInfo.country_code || '86'
			if (this.selectedCode != '86') {
				this.is86 = false
			}
		},
		methods: {
			test() {
				console.log(this.userInfo);
			},
			async testApi() {
				await db.collection('uni-id-users').where(`'email' == 'wjf5866@gmail.com'`).field('email').get().then(
					res => {
						console.log(res);
					})
			},
			...mapActions({
				getUserInfo: 'user/getUserInfo',
			}),
			toggleDropdown() {
				// console.log(123);
				this.dropdownVisible = !this.dropdownVisible; // 切换下拉框的可见性
			},
			selectCode(code) {
				this.selectedCode = code; // 设置选择的区号
				this.dropdownVisible = false; // 选择后隐藏下拉框
				setTimeout(() => {
					if (this.selectedCode == '86') {
						this.is86 = true
					} else {
						this.is86 = false
					}
				}, 0)
			},
			inputMobile(e) {
				setTimeout(() => {
					if (e == this.userInfo.mobile) {
						this.$uvToastWjf({
							message: ("输入的手机号码与原号码相同"),
							type: 'error'
						})
					}
				}, 0)
			},
			// 根据是否中国手机号分别操作
			preSubmit() {
				if (this.selectedCode == '86') {
					this.submit_86()
				} else {
					this.submitNot86()
				}
			},
			async submitNot86() {
				if (this.formData.mobile.trim() == '') {
					return this.$uvToastWjf({
						message: ("请输入正确手机号码"),
						type: 'error'
					})
				}
				if (this.userInfo.mobile == this.formData.mobile) {
					return this.$uvToastWjf({
						message: ("手机号未变更"),
						type: 'error'
					})
				}
				let res = await ap126Co.replaceMobileNot86({
					mobile: this.formData.mobile,
					country_code: this.selectedCode
				})
				if (!res.errCode && res.errMsg == 'success') {
					this.$uvToastWjf({
						message: ("已变更为新的手机号码"),
						type: 'success'
					}, () => {
						this.getUserInfo()
						uni.navigateBack()
					})
				}
			},
			submit_86() {
				this.$refs.form.validate().then(res => {
					this.confirmMobileSms(res)
				})
			},
			// 先校验短信验证码，
			confirmMobileSms(params) {
				const objWjf = uniCloud.importObject('uni-id-co')
				objWjf.replaceMobile({
					mobile: params.mobile,
					code: params.code
				}).then(res => {
					if (!res.errCode && res.errMsg == 'success') {
						this.confirmMobileUsed(params)
					}
				}).catch(e => {
					console.log(e);
				})
			},
			// 确认手机号码是否可用,如可用 就直接修改，否则返回已被使用的信息
			async confirmMobileUsed(params) {
				if (this.formData.mobile == this.userInfo.mobile) {
					this.$uvToastWjf({
						message: ("手机号未变更"),
						type: 'error'
					}, () => {
						this.formData.code = ''
						this.$refs.smsCode.getImageCaptcha(false)
						this.$refs.smsCode.captcha = ''
					})
					return
				}
				let res = await ap126Co.findUsedMobile({
					mobile: this.formData.mobile
				})
				if (res.usedNum) {
					this.$uvModal({
						content: ("该手机号码已被使用，请更换其他手机号码"),
						align: 'center',
					})
				} else {
					this.$uvToastWjf({
						message: ("已变更为新的手机号码"),
						type: 'success'
					}, () => {
						this.getUserInfo()
						uni.navigateBack()
					})
				}
			},
			upsateMobile() {
				let newUserInfo = Object.assign({}, this.userInfo, {
					mobile: this.formData.mobile
				})
			},

		}
	}
</script>

<style lang="scss">
	.container {
		max-width: 800px;
		height: 100vh;
		/* 设置最大宽度 */
		margin: 0 auto;
		/* 居中显示 */
		// padding: 20px;
		/* 添加内边距（可选） */
		background-color: rgba(240, 240, 240, 1);
	}

	.uni-button-group {
		position: fixed;
		bottom: calc(var(--window-bottom) + 40rpx);
		left: 70rpx;
		right: 70rpx;
		display: flex;

		// .uni-button {
		// 	flex: 1;
		// }
	}

	.uni-forms .uni-forms-item {
		background: #fff;
		padding: 6rpx;
		padding-left: 22rpx;
	}

	.note-box {
		padding: 20px;
		color: #555;
	}

	.phone-input {
		display: flex;
		align-items: center;
	}

	.country-code {
		// padding: 10px;
		// border: 1px solid #ccc;
		cursor: pointer;
		margin-right: 6rpx;
	}

	.dropdown {
		position: absolute;
		border: 1px solid #ccc;
		border-radius: 4rpx;
		background: white;
		z-index: 1000;
		width: 100rpx;
		/* 根据需要调整宽度 */
	}

	.dropdown-item {
		padding: 10rpx;
		cursor: pointer;
	}

	.dropdown-item:hover {
		background: #f0f0f0;
		/* 鼠标悬停时的效果 */
	}

	.not-86-box {
		margin-left: 50rpx;
		color: #f40;
	}
</style>